package cn.sumpu.app.guoguojie.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtil {

	private static final SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd");

	private final static Logger logger = LoggerFactory
			.getLogger(DateUtil.class);

	public static int getAge(String birthday) {
		if(Common.empty(birthday)) return 0;
		try {
			Date birthdayDate = sdf.parse(birthday);
			Calendar cal = Calendar.getInstance(Locale.CHINA);

			if (cal.before(birthdayDate)) {
				throw new IllegalArgumentException(
						"The birthDay is before Now.It's unbelievable!");
			}

			int yearNow = cal.get(Calendar.YEAR);
			int monthNow = cal.get(Calendar.MONTH);
			int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
			cal.setTime(birthdayDate);

			int yearBirth = cal.get(Calendar.YEAR);
			int monthBirth = cal.get(Calendar.MONTH);
			int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

			int age = yearNow - yearBirth;

			if (monthNow <= monthBirth) {
				if (monthNow == monthBirth) {
					// monthNow==monthBirth
					if (dayOfMonthNow < dayOfMonthBirth) {
						age--;
					} else {
						// do nothing
					}
				} else {
					// monthNow>monthBirth
					age--;
				}
			} else {
				// monthNow<monthBirth
				// donothing
			}
			return age;
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("Parse birthday failure!", e);
			}
			return 0;
		}
	}

//	public static void main(String[] args) {
//		System.out.println(DateUtil.getAge("1980-05-13"));
//	}
}
